
module.exports.getSigndParams = getSigndParams

var client = "ios";
var kAppKey = "8b790e0fb4484a17bd726dc4b060a0c8";
// var app = getApp();
var md5 = require('../pages/md5.js');

function getSigndParams(params) {

  // var retParams = JSON.parse(JSON.stringify(params));
  var retParams = {}
  for(var i = 0; i < params.length; i++){
    for(var key in params[i]) {
      console.log("params : " + key + " : " + params[i][key])
      retParams[key] = params[i][key]
    }
  }
  console.log("form sign util, retParam init = " + retParams)


  var exhibitionId = wx.getStorageSync('exhibitionid')

  // 设置表单中的 u 和 exhibitionid
  if (exhibitionId != null && !"".trim() == exhibitionId) {
    retParams["exhibitionid"] = exhibitionId
  }
  // debug
  // retParams["exhibitionid"] = 33

  var timestamp = Date.parse(new Date());
  timestamp = timestamp / 1000;
  retParams["timestamp"] = timestamp
  retParams["client"] = "ios"
  // 图片数据不参与签名
  var hasImg = (params["base64img"] != null && params["base64img"] != "")
  var imgStr = ""
  if (hasImg) {
    imgStr = params["base64img"]
    delete retParams["base64img"]
  }

  // 生成签名
  var sign = getSignWithParams(retParams)

  // 拼接剩余参数 sign   v   mac   u  lan  base64img    
  retParams["sign"] = sign
  retParams["v"] = "1.0.0"
  retParams["lan"] = "cn"

  if (hasImg) {
    retParams["base64img"] = imgStr
  }
  var userId = wx.getStorageSync('u')
  if (userId != null && !"".trim() == userId) {
    retParams["u"] = userId
  }
  // debug
  // retParams["u"] = 232

  return retParams
}

function getSignWithParams (jsonParam) {

  console.log(jsonParam)
  // 参数按字母排序, 并且将表单参数拼接为字符串
  var arr = [];
  for (var i in jsonParam) {
    if (jsonParam[i] == "") continue;

    arr.push((i + jsonParam[i]));
  }
  var sortedParamStr = arr.sort().join('')
  console.log("sortedParamStr = " + sortedParamStr)
  // 将 Token 拼接到参数前端和末尾
  var paramsWithSecretStr = kAppKey + sortedParamStr + kAppKey;
  console.log("paramsWithSecretStr = " + paramsWithSecretStr)
  // md5 签名
  var md5SignStr = md5.hexMD5(paramsWithSecretStr);
  console.log("md5SignStr = " + md5SignStr)

  return md5SignStr.toUpperCase();
}
